package com.shixun.controller;

import com.shixun.domain.Student;
import com.shixun.dto.StudentDto;
import com.shixun.dto.StudentOrPasswordDto;
import com.shixun.exception.exception.DormException;
import com.shixun.service.StudentService;
import com.shixun.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * ben
 * </p>
 *
 * @author shixun
 * @since 2023-06-10
 */
@RestController
@Slf4j
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;


    /**
     * 手动一条一条新增
     *
     * @return
     */
    @PostMapping("insert")
    @CacheEvict(value = "studentMsg",allEntries = true)
    public R insert(@RequestBody @Validated StudentDto studentDto) {
        return studentService.insertOne(studentDto);
    }


    /**
     * 导入文件新增
     */
    @PostMapping("insertMany")
    @CacheEvict(value = "studentMsg",allEntries = true)
    public R insertMany(MultipartFile file) {
        return studentService.insertByFile(file);
    }

    /**
     * 错误信息文件下载到浏览器，并清空服务器的错误文件
     */

    @Value("${dorm.path}")
    private String basePath;
    @Value("${dorm.errPath}")
    private String errPath;
//    @GetMapping
//    public void downErrFile(String errMsg, HttpServletResponse response) throws Exception {
//        log.info("位置{}",errMsg);
//        if (errMsg != null && !errMsg.equals("")) {
//            File file = new File(errMsg);
//            ServletOutputStream outputStream = response.getOutputStream();
//            FileInputStream inputStream = new FileInputStream(file);
//      //      response.setContentType("text/plain");
//            String uuid = UUID.randomUUID().toString();
//           response.addHeader("Content-Disposition", "attachment;filename=" + uuid + ".txt");
//            int len;
//            byte[] bytes = new byte[1024 * 1024 * 5];
//            while ((len = inputStream.read(bytes)) != -1) {
//                outputStream.write(bytes, 0, len);
//                outputStream.flush();
//            }
//            inputStream.close();
//            outputStream.close();
//          //  file.delete();
//        }
//    }


    @GetMapping
    public void downErrFile(String errMsg, HttpServletResponse response) throws Exception {
        String url=errPath+errMsg;
        if (errMsg != null && !errMsg.equals("")) {
            File file = new File(url);
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(file);
            response.setContentType("text/plain");
            String uuid = UUID.randomUUID().toString();
            response.addHeader("Content-Disposition", "attachment;filename=" + uuid + ".txt");
            int len;
            byte[] bytes = new byte[1024 * 1024 * 5];
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
            file.delete();
        }
    }
//@GetMapping
//public void downErrFile(String errMsg, HttpServletResponse response) throws Exception {
//    String url = errPath + errMsg;
//
//    File file = new File("/Users/xuchenbiao/Desktop/picture/学生名单.txt");
//    ServletOutputStream outputStream = response.getOutputStream();
//    FileInputStream inputStream = new FileInputStream(file);
//    response.setContentType("text/plain");
//    String uuid = UUID.randomUUID().toString();
//    response.addHeader("Content-Disposition", "attachment;filename=" + uuid +".txt");
//    int len;
//    byte[] bytes = new byte[1024 * 1024 * 5];
//    while ((len = inputStream.read(bytes)) != -1) {
//        outputStream.write(bytes, 0, len);
//        outputStream.flush();
//    }
//    inputStream.close();
//    outputStream.close();
// //   file.delete();
//}







    /**
     * 批量删除学生信息
     */

    @DeleteMapping("deleteStudents")
    @CacheEvict(value = "studentMsg",allEntries = true)
    public R deleteStudents(@RequestParam List<Long> ids) {
        studentService.removes(ids);
        return new R(1, "删除成功", null);
    }


    /**
     * 根据id查询单个学生信息
     *
     * @param id
     * @return
     */
    @GetMapping("select")
    public R selectOne(Long id) {
        Student student = studentService.getById(id);
        if (student == null) {
            throw new DormException("该学生不存在");
        }
        StudentDto studentDto = new StudentDto();
        BeanUtils.copyProperties(student, studentDto);
        return new R(1, "查询成功", studentDto);
    }

    /**
     * 修改学生信息
     */
    @PutMapping
    @CacheEvict(value = "studentMsg",allEntries = true)
    public R updateStudent(@RequestBody @Validated StudentOrPasswordDto studentOrPasswordDto,HttpSession session) {
       String student= (String) session.getAttribute("student");
        return studentService.updateStudent(studentOrPasswordDto);
    }

    /**
     * 学生信息分页查询
     */
    @GetMapping("/page")
    @Cacheable(value = "studentMsg",key = "'studentMsg_'+#page+'_'+#size+'_'+#name+'_'+#profession")
    public R page(int page,int size,String name,String profession)

    {
        return studentService.pageStudent(page,size,name,profession);
    }


}

